import datetime, hashlib, hmac, random
from urllib.parse import urlencode

def getSignatureKey(key, date_stamp, regionName, serviceName):
    kDate = hmac.new(('AWS4' + key).encode('utf-8'), date_stamp.encode("utf-8"), hashlib.sha256).digest()
#     print(kDate)
    kRegion = hmac.new(kDate, regionName.encode("utf-8"), hashlib.sha256).digest()
    kService = hmac.new(kRegion, serviceName.encode("utf-8"), hashlib.sha256).digest()
    kSigning = hmac.new(kService, 'aws4_request'.encode("utf-8"), hashlib.sha256).digest()
#     print(kSigning)
    return kSigning

def buildStrParams(params):
    url = ""
    for key, value in params.items():
        url += key + "=" + str(value) + "&"
    return url[:-1]  # 去除最后一个多余的"&"

def random_s():
    digits = '0123456789'
    ascii_letters = 'abcdefghigklmnopqrstuvwxyz'
    l = digits + ascii_letters
    str_list = [random.choice(l) for i in range(11)]
    random_str = ''.join(str_list)
#     print(random_str)
    return random_str

def generateAuthorization(secretAccessKey, region, service, canonical_querystring, amz_date, SessionToken, date_stamp, AccessKeyID):
        signing_key = getSignatureKey(secretAccessKey, date_stamp, region, service)
        canonical_headers = 'x-amz-date:' + amz_date + '\n' + 'x-amz-security-token:' + SessionToken + '\n'
        canonical_request = "GET" + '\n' + "/" + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + 'x-amz-date;x-amz-security-token' + '\n' + hashlib.sha256("".encode("utf-8")).hexdigest()
#         print(11)
#         print(canonical_request)
        algorithm = 'AWS4-HMAC-SHA256'
        credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
        string_to_sign = algorithm + '\n' +  amz_date + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
        Signature = hmac.new(signing_key, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
        data = f"AWS4-HMAC-SHA256 Credential={AccessKeyID}/{date_stamp}/{region}/{service}/aws4_request, SignedHeaders=x-amz-date;x-amz-security-token, Signature={Signature}"
#         data = f"AWS4-HMAC-SHA256 Credential=AKTPZWRiODlhOTgxZWJmNGUyNDkwMDAzZTc1NzA2MDNhZGI/20240406/cn-north-1/vod/aws4_request, SignedHeaders=x-amz-date;x-amz-security-token, Signature=acc727904772d2c385a3108d17be566221c32b1fbc2faf27d48a08d8c714bf15"
        return data

if __name__ == "__main__":
    auth = {
        "accessKeyId": "AKTPZTQ2MzNiMTczMWUxNDBhZGJmM2RmZTJhNjAyOTMzZDM",
        "secretAccessKey": "uQ0fzPTsYrUPRYCmFcJyJJVimThGk6fWwIdoN2uckdEVVoD4j/Hki3Y3apl8xdHG",
        "sessionToken": "STS2eyJMVEFjY2Vzc0tleUlEIjoiQUtMVFlqZGpZVFV3WldRd1pEVTBORFJtTW1Fd05XVTVObUUxTVRkaVl6VXlaVGciLCJBY2Nlc3NLZXlJRCI6IkFLVFBaVFEyTXpOaU1UY3pNV1V4TkRCaFpHSm1NMlJtWlRKaE5qQXlPVE16WkRNIiwiU2lnbmVkU2VjcmV0QWNjZXNzS2V5IjoiV09hYVVGM0ZuMnZ4V2RzVjNZVVVXYzNpM1FxWjVKSDMzTVg2WlRKSzk1ME5KaytZTERVVUwzbGplQy8zak1MWjlyUE5hSUFJRTkwM0IrNXpsdFRtTEFyRFFRVVcvRWRTbkpRM2IrNXBCTjQ9IiwiRXhwaXJlZFRpbWUiOjE3MTI1ODI4MjUsIlBvbGljeVN0cmluZyI6IntcIlN0YXRlbWVudFwiOlt7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJ2b2Q6KlwiLFwiSW1hZ2VYOipcIl0sXCJSZXNvdXJjZVwiOltcIipcIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlVzZXJJZFwiXSxcIlJlc291cmNlXCI6W1wiNjc1NjcyODc1OThcIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIkFwcElkXCJdLFwiUmVzb3VyY2VcIjpbXCIxMTI4XCJdfSx7XCJFZmZlY3RcIjpcIkFsbG93XCIsXCJBY3Rpb25cIjpbXCJVc2VyUmVmZXJlbmNlXCJdLFwiUmVzb3VyY2VcIjpbXCJ7XFxcInBzbVxcXCI6XFxcImRvdXlpbi5jcmVhdG9yLmNvbnRlbnRcXFwifVwiXX0se1wiRWZmZWN0XCI6XCJBbGxvd1wiLFwiQWN0aW9uXCI6W1wiU2Vzc2lvbkNoZWNrXCJdLFwiUmVzb3VyY2VcIjpbXCJVaWRcIl19LHtcIkVmZmVjdFwiOlwiQWxsb3dcIixcIkFjdGlvblwiOltcIlBTTVwiXSxcIlJlc291cmNlXCI6W1wiZG91eWluLmNyZWF0b3IuY29udGVudFwiXX1dfSIsIlNpZ25hdHVyZSI6IjVmNjkzZTNmYzMxMGRjYTJmMjQxNTMzZWJmNzQ3NzhkN2NlOGI0NzAxMjJhMjMzMjk5YWEzOTUzMTZmN2Q5NDEifQ=="
    }

    times = datetime.datetime.utcnow()
    amz_date = times.strftime('%Y%m%dT%H%M%SZ')
    print(amz_date)

    date_stamp = times.strftime('%Y%m%d')
#     print(date_stamp)
    region = 'cn-north-1'
    service = 'vod'

    s = random_s()
    params = {
        "Action": "ApplyUploadInner",
        "Version": "2020-11-19",
        "SpaceName": "aweme",
        "FileType": "video",
        "IsInner": 1,
        "FileSize": 3665189,
        "app_id" : 2906,
        "user_id" :"67567287598",
        "s" : s
    }

    print(s)

    canonical_querystring = buildStrParams(params)
    print(canonical_querystring)

    SessionToken = auth.get('sessionToken')
    AccessKeyID = auth.get('accessKeyId')
    secretAccessKey = auth.get('secretAccessKey')

    Authorization = generateAuthorization(secretAccessKey, region, service, canonical_querystring, amz_date, SessionToken, date_stamp, AccessKeyID)
    print(Authorization)
